package com.library.framework.security.provider;

import com.library.framework.security.provider.token.WechatAccountLoginAuthenticationToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @Package: com.educationalsystem.framework.security.provider
 * @ClassName: WechatAuthenticationProvider
 * @Author: Yin
 * @Date: 11:36
 * @Description: 微信账号登陆认证适配器
 */
@Slf4j
public class WechatAccountAuthenticationProvider implements AuthenticationProvider {

    /** WechatAccountDetailsServiceImpl */
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        /// 暂不需要
//        Map<String,Object> map = new HashMap<>();
//        map.put("username",wechatAccountLoginAuthenticationToken.getUsername());
//        map.put("password",wechatAccountLoginAuthenticationToken.getPassword());
//        map.put("code",wechatAccountLoginAuthenticationToken.getCode());

        WechatAccountLoginAuthenticationToken wechatAccountLoginAuthenticationToken = (WechatAccountLoginAuthenticationToken) authentication;
        // userNumber
        String username = wechatAccountLoginAuthenticationToken.getUsername();
        // login
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // 密码校验
        return new WechatAccountLoginAuthenticationToken(userDetails,wechatAccountLoginAuthenticationToken.getPassword(),userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return WechatAccountLoginAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

}
